package com.suse.common.util.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.ibatis.session.ResultHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 * EasyExcel工具类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-10-17 12:02
 */
public class EasyExcelUtil {

    public static <S> void bigDataExport(Consumer<ResultHandler<S>> consumer,
                                         ExcelWriter excelWriter) {
        try {
            WriteSheet[] writeSheet = new WriteSheet[] {
                    EasyExcel.writerSheet(0, "sheet").build()
            };
            List<S> list = new ArrayList<>(1000);
            // 0 代表当前的条数，等于100万时会被置为0
            // 1 代表已经有多少个一百万
            int [] c = new int[2];
            consumer.accept(data -> {
                c[0]++;
                list.add(data.getResultObject());
                if ((c[0] % 1000) == 0) {
                    excelWriter.write(list, writeSheet[0]);
                    list.clear();
                    if (c[0] == 1000000) {
                        c[1]++;
                        writeSheet[0] = EasyExcel.writerSheet(c[1], "sheet" + c[1]).build();
                        c[0] = 0;
                    }
                }
            });
            //可能有剩余的数据
            excelWriter.write(list, writeSheet[0]);
        } finally {
            excelWriter.finish();
        }
    }

}
